package com.sunny.ihealth.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sunny.ihealth.BaseActivity;
import com.sunny.ihealth.R;
import com.sunny.ihealth.ui.adapter.OnViewClickListener;
import com.sunny.ihealth.ui.adapter.PostDetailAdapter;
import com.sunny.ihealth.data.BmobManager;
import com.sunny.ihealth.entity.bmob.Comment;
import com.sunny.ihealth.entity.bmob.State;
import com.sunny.ihealth.entity.bmob.Post;
import com.sunny.ihealth.entity.eventbus.PostUpdateEvent;
import com.sunny.ihealth.utils.SoftInputUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class PostDetailActivity extends BaseActivity implements OnViewClickListener,
        SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    private static final String TAG = "TAG::PostDetailA";
    //一次加载多少
    private static final int LOAD_ITEM_SIZE = 10;

    private EditText etContent;
    private Button btnPublish;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayoutManager linearLayoutManager;
    private RecyclerView recyclerView;
    private PostDetailAdapter adapter;

    private Post post;
    private int position;
    private List<Comment> data;

    //标志位，是否正在加载数据
    private boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_detail);

        Intent intent = getIntent();
        if (intent == null || (post = (Post) intent.getSerializableExtra("data")) == null) {
            Toast.makeText(PostDetailActivity.this, "没有数据...", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "No Data When Start PostDetailActivity");
            return;
        }
        position = intent.getIntExtra("position", -1);

        initViews();

        //显示刷新图标
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                initData(0, LOAD_ITEM_SIZE, null);
            }
        }, 100);

    }

    @Override
    public void initViews() {
        setEnableBackIcon(true);
        setStatusBarColor();
        setToolbar("动态");

        etContent = (EditText) findViewById(R.id.editText_postDetail_content);
        btnPublish = (Button) findViewById(R.id.btn_postDetail_publish);
        btnPublish.setOnClickListener(this);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_postDetail);
        swipeRefreshLayout.setOnRefreshListener(this);

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        adapter = new PostDetailAdapter(this, post, data = new ArrayList<>());
        adapter.setListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_postDetail);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addOnScrollListener(onScrollListener);
        recyclerView.setAdapter(adapter);

    }


    /**
     * 加载数据
     *
     * @param skip  跳过多少
     * @param limit 加载多少
     */
    public void initData(final int skip, int limit, final Integer beforeID) {
        isLoading = true;

        getBmob().getComment(post.getObjectId(), skip, limit, beforeID, new BmobManager.Action1<List<Comment>>() {
            @Override
            public void onCompleted(List<Comment> comments) {
                if (comments.size() == 0) {
                    //Toast.makeText(PostDetailActivity.this, "啊偶，什么都没加载出来~", Toast.LENGTH_SHORT).show();
                } else {
                    if (beforeID == null) { //刷新
                        data.clear();
                        data.addAll(comments);
                    } else { //加载
                        data.addAll(comments);
                    }
                    adapter.notifyDataSetChanged();
                }
                isLoading = false;
                //延迟一段时间，隐藏刷新状态
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });
    }

    //RecyclerView的滑动状态监听
    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();

            //滑动到最后了
            if (lastVisiblePosition + 1 == adapter.getItemCount() &&
                    lastVisiblePosition != RecyclerView.NO_POSITION &&
                    dy > 0 &&
                    !swipeRefreshLayout.isRefreshing() &&
                    !isLoading &&
                    data.size() != 0 &&
                    post.getCommentNumber() > data.size()) {
                //刷新数据
                swipeRefreshLayout.setRefreshing(true);
                //下拉加载的数据，要加载的数据id<当前最后一个id
                initData(0, LOAD_ITEM_SIZE, data.get(data.size() - 1).getId());

            }
        }
    };

    @Override
    public void onViewClick(int viewID, final int position) {
        switch (viewID) {
            case R.id.btn_postDetail_like:
                getBmob().likePost(post.getObjectId(), new BmobManager.Action1<State>() {
                    @Override
                    public void onCompleted(State state) {
                        if (state.getState() > 0) {
                            if (state.getState() == State.STATE_DO_SUCCESSFUL) {
                                adapter.setLikeBtnText(true);
                            } else if (state.getState() == State.STATE_UNDO_SUCCESSFUL) {
                                adapter.setLikeBtnText(false);
                            }
                            //更新Zone界面
                            EventBus.getDefault().post(new PostUpdateEvent(PostDetailActivity.this.position, post));
                        }
                    }
                });
                break;
            case R.id.tv_postDetail_addFriend:
                getBmob().addFriend(post.getAuthor().getObjectId(), new BmobManager.Action1<State>() {
                    @Override
                    public void onCompleted(State state) {
                        if (state.getState() > 0) {
                            adapter.setIsFriend(state.getState());
                            //更新Zone界面
                            EventBus.getDefault().post(new PostUpdateEvent(PostDetailActivity.this.position, post));
                        }
                    }
                });
        }
    }

    @Override
    public void onRefresh() {
        initData(0, LOAD_ITEM_SIZE, null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_postDetail_publish:
                String content = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(PostDetailActivity.this, "先说点什么吧~", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (getBmob().checkState()) {
                    SoftInputUtils.hideSoftInput(this, etContent);
                    btnPublish.setEnabled(false);
                    getBmob().publishComment(post.getObjectId(), content, new BmobManager.Action1<Comment>() {
                        @Override
                        public void onCompleted(Comment comment) {
                            btnPublish.setEnabled(true);
                            if (comment != null) {
                                etContent.setText("");
                                Toast.makeText(PostDetailActivity.this, "评论成功~", Toast.LENGTH_SHORT).show();

                                post.setCommentNumber(post.getCommentNumber() + 1);
                                //更新Zone界面
                                EventBus.getDefault().post(new PostUpdateEvent(position, post));
                                data.add(0, comment);


                                adapter.notifyItemChanged(0, R.id.tv_postDetail_commentNumber);
                                //第一项是header
                                adapter.notifyItemInserted(1);
                            }
                        }
                    });
                }
                break;
        }
    }
}
